package org.example.util;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.text.PDFTextStripper;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;

public class PdfboxTest {
    // 提取PDF中的文本和图像
    private static void readTextAndImage(String filePath) {
        try (PDDocument document = Loader.loadPDF(new File(filePath))) {
            // 获取PDF文档的页数
            int numberOfPages = document.getNumberOfPages();

            // 遍历每一页提取文本和图像
            for (int i = 0; i < numberOfPages; i++) {
                PDPage page = document.getPage(i);

                // 提取页面文本
                PDFTextStripper textStripper = new PDFTextStripper();
                textStripper.setStartPage(i + 1);
                textStripper.setEndPage(i + 1);
                String pageText = textStripper.getText(document);
                System.out.println("Page " + (i + 1) + " Content: \n" + pageText + "\n");

                // 提取图像资源
                PDResources resources = page.getResources();
                for (COSName xObjectName : resources.getXObjectNames()) {
                    if (resources.isImageXObject(xObjectName)) {
                        PDImageXObject imageObject = (PDImageXObject) resources.getXObject(xObjectName);
                        BufferedImage bImage = imageObject.getImage();

                        // 将图像保存为 PNG 格式
                        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
                            ImageIO.write(bImage, "png", baos);
                            byte[] imageBytes = baos.toByteArray();
                            String imageFilePath = "image_" + System.currentTimeMillis() + ".png";
                            try (FileOutputStream fos = new FileOutputStream(imageFilePath)) {
                                fos.write(imageBytes);
                                System.out.println("Page " + (i + 1) + " Image saved: " + imageFilePath);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // 输入PDF文件路径
        String filePath = "C:\\Users\\30147\\Desktop\\GZ031.pdf";
        readTextAndImage(filePath);
    }
}
